package com.example.home.findWork.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.home.R;
import com.example.home.findWork.adapter.ViewapteTool;
import com.example.home.findWork.adapter.WordAllAdapter;
import com.example.home.findWork.adapter.WordHotAdapter;
import com.example.home.findWork.adapter.WordNameAdapter;
import com.example.home.findWork.bean.ProfessionBean;
import com.example.home.findWork.bean.WordHotBean;
import com.example.home.findWork.bean.WorkBannerBean;
import com.example.home.tool.OKHttpTool;
import com.example.home.tool.RunOnUiThreadTool;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class WorkFragment extends Fragment {
    private ViewPager vpBanner;
    private SearchView sear;
    private RecyclerView tabList;
    private RecyclerView rcvList;
    private RecyclerView rcv_hotlist;
    private String oldUrl = "prod-api/api/job/post/list";
    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_work, container, false);
        initView();
        getBanner();

        getHotList();

        getProfessionName();

        getAllListWithUrl(oldUrl);
        return view;
    }

    private void getProfessionName() {
        OKHttpTool.doNetRequest("prod-api/api/job/profession/list",
                OKHttpTool.GET,
                ProfessionBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        ProfessionBean professionBean = (ProfessionBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                bindNameList(professionBean);
                            }
                        });
                    }


                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void bindNameList(ProfessionBean professionBean) {
        // 通过 Set 来实现去重
        Set<String> uniqueNames = new HashSet<>();
        List<ProfessionBean.RowsBean> uniqueList = new ArrayList<>();

        for (ProfessionBean.RowsBean rowsBean : professionBean.getRows()) {
            String itemName = rowsBean.getProfessionName();
            if (itemName != null && uniqueNames.add(itemName)) {
                uniqueList.add(rowsBean);
            }
        }

        WordNameAdapter wordNameAdapter = new WordNameAdapter(getActivity(), uniqueList, new WordNameAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String itemName, int itemId) {
                Log.v("xhf", "id=" + itemId);
                if (itemId != WordNameAdapter.DEFAULT_ID) {
                    String newUrl = "prod-api/api/job/post/list?name=" + itemName;
                    // 在这里进行网络请求，可以使用新的 URL
                    getAllListWithUrl(newUrl);
                } else if ("所有职位".equals(itemName)) {
                    // 如果点击的是 "所有职位"，显示所有数据
                    getAllListWithUrl(oldUrl);
                } else {
                    // 如果 ID 为默认值，显示所有数据
                    getAllListWithUrl(oldUrl);
                }
            }
        });

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        tabList.setAdapter(wordNameAdapter);
        tabList.setLayoutManager(gridLayoutManager);
    }



    private void getAllListWithUrl(String url) {
        OKHttpTool.doNetRequest(url, OKHttpTool.GET, WordHotBean.class, new OKHttpTool.NetCallback() {
            @Override
            public void onSuccess(Object obj) {
                WordHotBean wordHotBean = (WordHotBean) obj;
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (wordHotBean.getTotal() == 0){
                            Toast.makeText(getActivity(),"暂无该分类职位",Toast.LENGTH_SHORT).show();
                        }else {
                            bindAllList(wordHotBean);
                        }
                    }
                });
            }

            @Override
            public void onFailure(String msg) {
                // 处理请求失败的逻辑
            }
        });
    }

    private void bindAllList(WordHotBean wordHotBean) {
        WordAllAdapter wordHotAdapter = new WordAllAdapter(getActivity(),wordHotBean.getRows());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        rcvList.setAdapter(wordHotAdapter);
        rcvList.setLayoutManager(linearLayoutManager);
    }

    private void getHotList() {
        OKHttpTool.doNetRequest("prod-api/api/job/post/list",
                OKHttpTool.GET,
                WordHotBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        WordHotBean wordHotBean = (WordHotBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                bindHotList(wordHotBean);
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void bindHotList(WordHotBean wordHotBean) {
        WordHotAdapter wordHotAdapter = new WordHotAdapter(getActivity(),wordHotBean.getRows());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        rcv_hotlist.setAdapter(wordHotAdapter);
        rcv_hotlist.setLayoutManager(linearLayoutManager);
    }

    private void getBanner() {
        OKHttpTool.doNetRequest("prod-api/api/rotation/list",
                OKHttpTool.GET,
                WorkBannerBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        WorkBannerBean workBannerBean = (WorkBannerBean)obj;
                        RunOnUiThreadTool.run(WorkFragment.this.getActivity(), new RunOnUiThreadTool.RunCallback() {
                            @Override
                            public void set() {
                                ArrayList<String> list = new ArrayList<>();
                                for (int i = 0; i < workBannerBean.getRows().size(); i++) {
                                    list.add(workBannerBean.getRows().get(i).getAdvImg());
                                }
                                ViewapteTool viewapteTool = new ViewapteTool(WorkFragment.this.getActivity(),list);
                                vpBanner.setAdapter(viewapteTool);
                                mHandler.sendEmptyMessageDelayed(0, 3 * 1000);
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                }
        );
    }

    private android.os.Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                int index = vpBanner.getCurrentItem();
                index = (index + 1) % 3;
                vpBanner.setCurrentItem(index);
                mHandler.sendEmptyMessageDelayed(0, 3 * 1000);
            }
        }
    };

    private void initView() {

        vpBanner = view.findViewById(R.id.vp_banner);
        sear = view.findViewById(R.id.sear);
        tabList = view.findViewById(R.id.tab_list);
        rcvList = view.findViewById(R.id.rcv_list);
        rcv_hotlist = view.findViewById(R.id.rcv_hotlist);

        sear.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 用户提交搜索时调用
                performSearch(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // 用户输入搜索关键字时调用
                // 在这里可以实时处理搜索建议等操作
                return true;
            }
        });

        sear.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                // 用户点击搜索框内的关闭按钮时调用
                // 在这里处理关闭按钮的操作，比如重新加载所有数据
                reloadAllData();
                return false; // 返回 false 表示继续执行默认操作
            }
        });


    }

    private void reloadAllData() {
        // 重新加载所有数据的操作
        getAllListWithUrl(oldUrl);
    }

    private void performSearch(String query) {
        // 执行搜索操作
        String searchUrl = "prod-api/api/job/post/list?name=" + query;
        getAllListWithUrl(searchUrl);
    }
}